package com.ittest.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.ittest.domain.system.Permission;
import com.ittest.service.system.PermissionService;
import com.ittest.service.system.impl.PermissionServiceImpl;
import com.ittest.utils.BeanUtil;
import com.ittest.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/system/permission/*")
public class PermissionServlet extends BaseServlet {
    // 获取服务层对象
    private PermissionService service = new PermissionServiceImpl();

    // 分页查询
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置分页数据
        int page = 1;
        int size = 10;
        // 判断从前端获取的数据
        if (StringUtils.isNotBlank(req.getParameter("page"))){
            page = Integer.parseInt(req.getParameter("page"));
        }
        if (StringUtils.isNotBlank(req.getParameter("size"))) {
            size = Integer.parseInt(req.getParameter("size"));
        }
        //调用service层,查询数据
        List<Permission> list = service.findAll(page, size);
        // 设置分页插件
        PageInfo<Permission> pageInfo = new PageInfo<>(list);
        //数据存到request域中
        req.setAttribute("size",size);
        req.setAttribute("page",pageInfo);
        //跳转到页面
        req.getRequestDispatcher("/pages/system/permission/permission-list.jsp").forward(req,resp);
    }
    // 跳转到添加页面
    protected void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 页面跳转
        req.getRequestDispatcher("/pages/system/permission/permission-add.jsp").forward(req,resp);
    }
    // 新增
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的数据,并封装
        Permission permission = BeanUtil.fillBean(req, Permission.class);
        // 调用业务层方法
        service.save(permission);
        // 页面跳转
        req.getRequestDispatcher("/system/permission/list").forward(req,resp);
    }
    // 删除
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的id
        String id = req.getParameter("id");
        // 调用删除方法
        service.delete(id);
        // 页面跳转
        req.getRequestDispatcher("/system/permission/list").forward(req,resp);

    }
    // 批量删除
    protected void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传来的id
        String id = req.getParameter("id");
        // 调用删除方法
        service.deleteById(id);
        // 页面跳转
        req.getRequestDispatcher("/system/permission/list").forward(req,resp);

    }
}
